/**
 * Created by John on 2016/7/1.
 */
var demo = new sample();

// demo.log();

demo.cluster();

function sample() {
    this.log = function () {
        var fs = require('fs');
        var accessLogfile = fs.createWriteStream('access.log', {flags: 'a'});
        var errorLogfile = fs.createWriteStream('error.log', {flags: 'a'});

        var logger = require('morgan');
        var express = require('express');
        var app = express();

        app.use(logger({stream: accessLogfile}));
        app.use(function (req, res, next) {
            var err = new Error('Not Found');
            err.status = 404;

            var meta = '[' + new Date() + ']' + req.url + '\n';
            errorLogfile.write(meta + err.stack + '\n');
            next(err);
        });

        app.listen(3000);
    };

    this.cluster = function () {
        var express = require('express');
        var app = express();
        app.set('env', 'production');

        if (!module.parent) {
            app.listen(3000);
            console.log('Express server listening on port %d in %s mode',
                app.get('port'),
                app.get('env')
            );
        }

        var cluster = require('cluster');
        var os = require('os');
        var numCPUs = os.cpus().length;

        var workers = {};
        if (cluster.isMaster) {
            cluster.on('death', function (worker) {
                delete workers[worker.pid];
                worker = cluster.fork();
                workers[worker.pid] = worker;
            });

            for (var i = 0; i < numCPUs; i++) {
                var worker = cluster.fork();
                workers[worker.pid] = worker;
            }
        } else {
            app = require('./app');
            app.listen(3000);
        }

        process.on('SIGTERM', function () {
            for (var pid in workers) {
                process.kill(pid);
            }
        });
    }
}